package com.nti56.springboot.service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.nti56.springboot.annotation.SystemServiceLog;
import com.nti56.springboot.exception.MyRuntimeException;
import com.nti56.springboot.mapper.tmsmapper.RoleMapper;
import com.nti56.springboot.mapper.tmsmapper.UserMapper;
import com.nti56.springboot.model.Role;
import com.nti56.springboot.model.User;
import com.nti56.springboot.model.UserRole;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.MD5Util;
import com.nti56.springboot.utils.ParamUtil;
import com.nti56.springboot.utils.ParamUtil.Param;


@Service
public class UserService {
	
	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	@Autowired
    private UserMapper userMapper;
	
	@Autowired
    private RoleMapper roleMapper;
	
	public User getById(String userId){
		return userMapper.getById(userId);
	}
	
	public List<User> findAll(Map params) {
		return userMapper.findAll(params);
	}
	
	public List<User> getUserList(Map params) {			
		List<User> userList = userMapper.getUserList(params);
		for(User u : userList){
			List<Role> roleList = this.getRoleListByUserId(u.getUserId(),Constant.SYS_ROLE_TYPE_OPERATE);
			u.setRoles(new HashSet(roleList));
			List<Role> dataRoleList = this.getRoleListByUserId(u.getUserId(),Constant.SYS_ROLE_TYPE_DATA_AUTH);
			u.setDataRoles(new HashSet(dataRoleList));
		}
		return userList;
	}
	
	/**
	 * 根据用户ID ，查询角色
	 * @param userId
	 * @return
	 */
	public List<Role> getRoleListByUserId(String userId,String roleType){
		Param map = ParamUtil.setParam("userId", userId).setParam("roleType", roleType);
		List<Role> roleList = roleMapper.getRoleListByUserId(map);
		return roleList;
	}
	
	public User findByUserName(String userName) {
		return userMapper.findByUserName(userName);
	}
	
	public User findUserAuth(String userName) {
		return userMapper.findUserAuth(userName);
	}
	
	@SystemServiceLog(description = "新增用户信息")
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void savaUser(User u ,List<Role> roleList){
		int cnt = userMapper.selectCnt(u.getUserName());
		if(cnt > 0){
			logger.error("用户名:"+u.getUserName()+" 已经存在请勿重复添加!");
			throw new MyRuntimeException("用户名:"+u.getUserName()+" 已经存在请勿重复添加!");
		}
		userMapper.insert(u);
		for(Role r : roleList){
			UserRole ur = new UserRole();
			ur.setUserId(u.getUserId());
			ur.setRoleId(r.getRoleId());
			userMapper.insertUserRole(ur);
		}
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager") 
	public void updateUser(User u ,String roleType,List<Role> roleList){
		userMapper.update(u);
		Param map = ParamUtil.setParam("userId",u.getUserId()).setParam("roleType", roleType);
		roleMapper.deleteUserRoleByUserId(map);
		if(roleList!=null && roleList.size()>0) {
			UserRole ur = null;
			for(Role r : roleList){
				ur = new UserRole();
				ur.setUserId(u.getUserId());
				ur.setRoleId(r.getRoleId());
				userMapper.insertUserRole(ur);
			}
		}
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager") 
	public void deleteUser(String userId){
		User user = userMapper.getById(userId);
		if(user.getUserName().equalsIgnoreCase(Constant.SYSTEM_SUPER_ADMIN_NAME)){
			logger.error("系统不允许手动删除超级管理员用户!");
			throw new MyRuntimeException("系统不允许手动删除超级管理员用户!");
		}
		Param map = ParamUtil.setParam("userId",userId);
		roleMapper.deleteUserRoleByUserId(map);
		userMapper.delete(userId);
	}
	
	/**
	   * 用户自身重置密码
	 * @param map
	 */
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager") 
	public void restSelfPwd(Map map) {
		String userId = (String)map.get("userId");
		String password = (String)map.get("password");
		String newPassword = (String)map.get("newPassword");
		String regPassword = (String)map.get("regPassword");
		User user = userMapper.getById(userId);
		if(StringUtil.isEmpty(password) 
				|| StringUtil.isEmpty(newPassword)
				|| StringUtil.isEmpty(regPassword)) {
			throw new MyRuntimeException("密码不能为空!");
		}
		if(!user.getPassWord().equals(MD5Util.MD5(password))) {
			throw new MyRuntimeException("原密码不正确，不允许修改!");
		}
		if(!newPassword.equals(regPassword)) {
			throw new MyRuntimeException("新密码和确认密码不一致，不允许修改!");
		}
		if(MD5Util.MD5(newPassword).equals(user.getPassWord())){
			throw new MyRuntimeException("新密码不能和原密码一样!");
		}
		user.setPassWord(MD5Util.MD5(newPassword));
		userMapper.update(user);
	}
	
	/**
	   * 修改用户密码
	 * @param map
	 */
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager") 
	public void restUserPwd(Map map) {
		String userId = (String)map.get("userId");		
		String newPassword = (String)map.get("newPassword");
		String regPassword = (String)map.get("regPassword");
		User user = userMapper.getById(userId);
		if(StringUtil.isEmpty(newPassword)
				|| StringUtil.isEmpty(regPassword)) {
			throw new MyRuntimeException("密码不能为空!");
		}		
		if(!newPassword.equals(regPassword)) {
			throw new MyRuntimeException("新密码和确认密码不一致，不允许修改!");
		}
		user.setPassWord(MD5Util.MD5(newPassword));
		userMapper.update(user);
	}
}
